import random

from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework.response import Response
from celery_tasks.sms_code.tasks import send_sms_code
from rest_framework.generics import CreateAPIView
from rest_framework.generics import RetrieveAPIView, UpdateAPIView
from users import serializers
from users.models import User
from users.serializers import UserShowSerializers, UserEmailSerializers
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


class SMS_Code_View(APIView):
    def get(self, request, mobile):
        # 建立连接
        conn = get_redis_connection('sms_code')
        flag = conn.get('sms_code_%s' % mobile)
        if flag:
            return Response({'error': "请求过于频繁"}, status=403)
        sms_code = "%06d" % random.randint(0, 999999)
        print(sms_code)
        conn = get_redis_connection('sms_code')
        # 设置管道
        pl = conn.pipeline()
        pl.setex('sms_code_$%s' % mobile, 300, sms_code)
        pl.setex('sms_code_%s' % mobile, 60, 1)
        pl.execute()
        # send_sms_code.delay(mobile, sms_code)
        # t = Thread(target=send_sms_code, args=(mobile, sms_code))
        # t.start()
        return Response("ok")


class UserNameView(APIView):
    def get(self, request, username):
        #  计算数量
        count = User.objects.filter(username=username).count()
        return Response({"count": count})


class MobileView(APIView):
    def get(self, request, mobile):
        #  计算数量
        count = User.objects.filter(mobile=mobile).count()
        return Response({"count": count})


class UserView(CreateAPIView):
    serializer_class = serializers.UserSerializers


# 用户中心展示
class UserShowView(RetrieveAPIView):
    serializer_class = UserShowSerializers
    queryset = User.objects.all()

    #     重写
    def get_object(self):
        #   jwt方法根据前端传递过来得请求头判断中是否有token解密后传递给request
        return self.request.user


# 保存更新邮箱
class UserEmailView(UpdateAPIView):
    serializer_class = UserEmailSerializers

    def get_object(self):
        #   jwt方法根据前端传递过来得请求头判断中是否有token解密后传递给request
        return self.request.user


class UserEmailVifyView(APIView):
    """
        邮箱验证
        获取前端数据
        解密token
        获取查询后得用户对象
        根据用户查询用户对象
        跟新用户邮箱验证状态
        返回验证状态
    """

    def get(self, request):
        token = request.query_params.get('token')
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except:
            return Response({'errors': '错误的token'}, status=400)
        username = data.get('username')
        user = User.objects.get(username=username)
        User.email_active = True
        user.save()
        return Response({'email_active': user.email_active})
